package server.business.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import server.business.mapper.BloodDispenseMapper;
import server.business.mapper.BloodDispenseReviewMapper;
import server.business.mapper.BloodSamplePatientMapper;
import server.business.mapper.TransfusionApplicationInformationMapper;
import server.business.pojo.*;
import server.business.utils.PageResult;
import server.business.utils.Result;
import server.business.service.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 配血审核
 */
@Controller
@RequestMapping("/bloodDispenseReview")
public class BloodDispenseReviewController {
    @Autowired
    private BloodDispenseService bloodDispenseService;
    @Autowired
    private BloodDispenseReviewMapper bloodDispenseReviewMapper;
    @Autowired
    private BloodDispenseReviewService bloodDispenseReviewService;

    @Autowired
    private BloodSampleService bloodSampleService;
    @Autowired
    private OverallBloodService overallBloodService;
    @Autowired
    private BloodInformationService bloodInformationService;
    @Autowired
    private BloodTestService bloodTestService;
    @Autowired
    private BloodDispenseMapper bloodDispenseMapper;
    @Autowired
    private BloodSamplePatientMapper bloodSamplePatientMapper;
    @Autowired
    private TransfusionApplicationInformationService transfusionApplicationInformationService;
    @Autowired
    private TransfusionApplicationInformationMapper transfusionApplicationInformationMapper;


    /**
     * 获取页面
     * 配血审核分页查询
     */
    @RequestMapping("/review/listByPage")
    @ResponseBody
    public PageResult getPagBloodDispenseReview(HttpServletRequest request, HttpServletResponse response) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        Page<BloodDispenseVo> page = new Page<>(currentPage,pageSize);
        QueryWrapper<BloodDispenseVo> queryWrapper=new QueryWrapper<>();
        IPage<BloodDispenseVo> samplePage = bloodDispenseReviewMapper.selectBloodDispenseReviewByPage(page,queryWrapper);
        PageResult pageResult = new PageResult("200", "成功", samplePage.getRecords(), currentPage, pageSize,
                samplePage.getTotal(), samplePage.getPages());
        List<BloodDispenseVo> bloodDispenseVo=page.getRecords();
        return pageResult;
    }


    /**
     * 审核
     * @param bloodDispenseVo
     * @return
     */
    @RequestMapping("/review/review")
    @ResponseBody
    public Result reviewBloodDispense(@RequestBody BloodDispenseVo bloodDispenseVo) throws Exception{

        //审核登记
        BloodTestReview bloodDispenseReview= bloodDispenseReviewMapper.selectByBloodDispenseId(bloodDispenseVo.getId());
        bloodDispenseReview.setReviewerId(bloodDispenseVo.getReviewerNumber());
        bloodDispenseReview.setReviewTime(bloodDispenseVo.getReviewTime());
        bloodDispenseReview.setRejectReason(bloodDispenseVo.getRejectReason());
        bloodDispenseReview.setReviewTime(new Date());
        bloodDispenseVo.setReviewTime(new Date());
        Result result = new Result();
        System.out.println();
        if(bloodDispenseVo.getStatue().equals("审核通过")){
            bloodDispenseVo.setStatue("5");
            bloodDispenseReview.setState("2");
//            血袋信息弃用
//            //根据血液样本编号找到血液编号，再根据血液编号找到血液信息
//            BloodSample bloodSample=bloodSampleService.getOne(new QueryWrapper<BloodSample>().eq("number",
//                    bloodDispenseVo.getBloodNumber()));
//            BloodInformation bloodInformation =bloodInformationService.getOne(new QueryWrapper<BloodInformation>().eq(
//                    "blood_id",bloodSample.getBloodNumber()));
//            OverallBlood overallBlood=overallBloodService.getOne(new QueryWrapper<OverallBlood>().eq(
//                    "blood_dispense_number",bloodDispenseVo.getNumber()));
//            String bagInformation;
//            if(overallBlood.getBloodBagInformation().equals("")){
//                bagInformation="血液ID:"+bloodInformation.getBloodId();
//            }
//            else {
//                bagInformation=overallBlood.getBloodBagInformation()+";"+bloodInformation.getBloodId();
//            }
//                overallBlood.setBloodBagInformation(bagInformation);
//                overallBloodService.updateById(overallBlood);
        }else if(bloodDispenseVo.getStatue().equals("驳回")){
            bloodDispenseReview.setState("3");
            bloodDispenseVo.setStatue("4");
        }
        bloodDispenseReviewService.updateById(bloodDispenseReview);
        BloodDispense bloodDispense=new BloodDispense();
        BeanUtils.copyProperties(bloodDispenseVo,bloodDispense);
        boolean success = bloodDispenseService.updateById(bloodDispense);
        if(success) {
            result.setCode("200");
            result.setMsg("审核成功");
        }else{
            result.setCode("500");
            result.setMsg("审核失败");
        }
        return result;
    }


    /**
     * 配血审核搜索
     *
     * @param request  请求
     * @param response 响应
     * @return {@link PageResult}
     */
    @RequestMapping("/review/reviewSearch")
    @ResponseBody
    public PageResult bloodDispenseReviewSearch(HttpServletRequest request, HttpServletResponse response){

        //查询条件
        String number = request.getParameter("number");
        String inspectionSheet = request.getParameter("inspectionSheet");
        String medicalRecordNumber = request.getParameter("medicalRecordNumber");
        String name = request.getParameter("name");
        String bloodSampleNumber = request.getParameter("bloodSampleNumber");
        String bloodNumber = request.getParameter("bloodNumber");
        String dispenseMethod = request.getParameter("dispenseMethod");
        String reviewerNumber = request.getParameter("reviewerNumber");
        String reviewerName = request.getParameter("reviewerName");
        String startReviewTime = request.getParameter("startReviewTime");
        String endReviewTime = request.getParameter("endReviewTime");
        String statue = request.getParameter("statue");
        String reviewState = request.getParameter("reviewState");
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));

        Page<BloodDispenseVo> page = new Page<>(currentPage, pageSize);
//        //创建查询条件
        QueryWrapper<BloodDispenseVo> queryWrapper = new QueryWrapper<>();
        //单据号
        if (number != "")
            queryWrapper.like("a.number", number);
        //检验单号
        if (inspectionSheet != "")
            queryWrapper.eq("inspection_sheet", inspectionSheet);
        //病历号
        if (medicalRecordNumber != ""){
            queryWrapper.like("medical_record_number", medicalRecordNumber);
        }
        //姓名
        if (name != "")
            queryWrapper.like("name",name);
        //血液样本编号
        if (bloodSampleNumber != "")
            queryWrapper.like("blood_sample_number", bloodSampleNumber);
//        血液样本编号
        if (bloodNumber != "")
            queryWrapper.like("d.number",bloodNumber);
        //审核人工号
        if (reviewerNumber != "")
            queryWrapper.like("a.reviewer_number", reviewerNumber);
        //审核人
        if (reviewerName != "")
            queryWrapper.like("a.reviewer_name", reviewerName);
        //审核时间
        if(startReviewTime != "")
            queryWrapper.ge("a.review_time", startReviewTime);
        if(endReviewTime != "")
            queryWrapper.le("a.review_time", endReviewTime);
        //配血方法
        if (dispenseMethod!= "")
            queryWrapper.eq("dispense_method", dispenseMethod);
        //审核状态
        if (reviewState != "")
            queryWrapper.eq("f.state",reviewState);

        BloodDispenseVo bloodDispenseVo=new BloodDispenseVo();
        //查询数据库
        bloodDispenseReviewMapper.selectBloodDispenseReviewByPage(page, queryWrapper);

        //返回的数据
        PageResult sampleDataVo = new PageResult("200", "成功", page.getRecords(), currentPage, pageSize, page.getTotal(), page.getPages());
        System.out.println(page.getTotal());
        sampleDataVo.setCode("200");
        sampleDataVo.setMsg("搜索成功");
        return sampleDataVo;
    }

    /**
     * 下载excel
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/review/downloadExcel")
//    @ResponseBody
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response){

        //查询条件
        String number = request.getParameter("number");
        String inspectionSheet = request.getParameter("inspectionSheet");
        String medicalRecordNumber = request.getParameter("medicalRecordNumber");
        String name = request.getParameter("name");
        String bloodSampleNumber = request.getParameter("bloodSampleNumber");
        String bloodNumber = request.getParameter("bloodNumber");
        String dispenseMethod = request.getParameter("dispenseMethod");
        String reviewerNumber = request.getParameter("reviewerNumber");
        String reviewerName = request.getParameter("reviewerName");
        String startReviewTime = request.getParameter("startReviewTime");
        String endReviewTime = request.getParameter("endReviewTime");
        String statue = request.getParameter("statue");
        String reviewState = request.getParameter("reviewState");

        Result result = new Result();
        try {
            String filename = "交叉配血审核";
            String userAgent = request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
                filename = URLEncoder.encode(filename,"UTF-8");            }else {
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            response.setContentType("application/json.ms-exce");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition","filename = " + filename + ".xlsx");

            //创建查询条件
            QueryWrapper<BloodDispenseVo> queryWrapper = new QueryWrapper<>();
            //单据号
            if (number != "")
                queryWrapper.like("a.number", number);
            //检验单号
            if (inspectionSheet != "")
                queryWrapper.eq("inspection_sheet", inspectionSheet);
            //病历号
            if (medicalRecordNumber != ""){
                queryWrapper.like("medical_record_number", medicalRecordNumber);
            }
            //姓名
            if (name != "")
                queryWrapper.like("name",name);
            //血液样本编号
            if (bloodSampleNumber != "")
                queryWrapper.like("blood_sample_number", bloodSampleNumber);
//        血液样本编号
            if (bloodNumber != "")
                queryWrapper.like("d.number",bloodNumber);
            //审核人工号
            if (reviewerNumber != "")
                queryWrapper.like("a.reviewer_number", reviewerNumber);
            //审核人
            if (reviewerName != "")
                queryWrapper.like("a.reviewer_name", reviewerName);
            //审核时间
            if(startReviewTime != "")
                queryWrapper.ge("a.review_time", startReviewTime);
            if(endReviewTime != "")
                queryWrapper.le("a.review_time", endReviewTime);
            //配血方法
            if (dispenseMethod!= "")
                queryWrapper.eq("dispense_method", dispenseMethod);
            //审核状态
            if (reviewState != "")
                queryWrapper.eq("review_state",reviewState);

            BloodDispenseVo bloodDispenseVo=new BloodDispenseVo();

            //查询数据库
            List<BloodDispenseReview> bloodTestVoList=
                    bloodDispenseReviewMapper.selectBloodDispenseReviewExcel(queryWrapper);

            EasyExcel.write(response.getOutputStream(),BloodDispenseReview.class).sheet("sheet").doWrite(bloodTestVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
